package
{
	import flash.events.*;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	public class FBHttpPost
	{
		protected var fCallback:Function;
		public static function Encode(s:String):String
		{
			return encodeURIComponent(s);
		}
		public static function Decode(s:String):String
		{
			return decodeURIComponent(s);
		}
		public function FBHttpPost(f:Function)
		{
			fCallback = f;
		}
		
		
		public function Post(url:String, data:String):void
		{
			var loader:URLLoader = new URLLoader(); 
			loader.dataFormat = URLLoaderDataFormat.TEXT;
			configureListeners(loader);
			//var request:URLRequest = new URLRequest("http://aafgcveb.facebook.joyent.us/index.php");
			var request:URLRequest = new URLRequest(url);
			//var request:URLRequest = new URLRequest("http://aafgcveb.facebook.joyent.us/login.php?username=player1&password=12344");
			//var request:URLRequest = new URLRequest("http://aagntw29.facebook.joyent.us/game/php/rest.php");
			var variables:URLVariables = new URLVariables();
			if(data != "")
				variables.decode(data);
			
			//variables.data = Encode("id="+FBGame.UserID+"&"+data);
			request.data = variables;
			request.method = URLRequestMethod.POST;
			try {
				loader.load(request);
			} catch (error:Error) {
				trace("Unable to load requested document.");
				fCallback("Request fail", false);
			}
		}
		private function configureListeners(dispatcher:IEventDispatcher):void {
			dispatcher.addEventListener(Event.COMPLETE, completeHandler);
			dispatcher.addEventListener(Event.OPEN, openHandler);
			dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
			dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
			dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		}
		private function completeHandler(event:Event):void {
			var loader:URLLoader = URLLoader(event.target);
			trace("completeHandler: " + loader.data);
			fCallback(loader.data,true);
		}
		
		private function openHandler(event:Event):void {
			//trace("openHandler: " + event);
		}
		
		private function progressHandler(event:ProgressEvent):void {
			//trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
		}
		
		private function securityErrorHandler(event:SecurityErrorEvent):void {
			trace("securityErrorHandler: " + event);
			fCallback("securityErrorHandler", false);
		}
		
		private function httpStatusHandler(event:HTTPStatusEvent):void {
			//trace("httpStatusHandler: " + event);
		}
		
		private function ioErrorHandler(event:IOErrorEvent):void {
			trace("ioErrorHandler: " + event);
			fCallback("ioErrorHandler: " + event, false);
		}
	}
}